package com.lihaichen.utils.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author rli
 */
public class ConfigHelper {

    public static final String DEFAULT_CONFIGURATION_PATH = "conf/healthcheck.xml";
    public static final String DEFAULT_TESTDATA_NAME = "td001";
    public static final String DEFAULT_TEST_ENVIRONMENT = "Dev";
    //TODO plan B if the default in not configured in server path.
    private static final String BUILD_IN_CONGIFUATION_PATH="healthcheck.xml";

    private static final Logger logger = LoggerFactory.getLogger(ConfigHelper.class.getName());

    XMLConfiguration _config = null;
    public XMLConfiguration getConfig() {
        return _config;
    }

    private String _currentEnvironment = DEFAULT_TEST_ENVIRONMENT;
    public String getCurrentEnvironment() {
        return _currentEnvironment;
    }
    

  //=========================================================================
  // Constructor
  //=========================================================================
   
    public ConfigHelper(){
        try {
            logger.info("Loading {}",DEFAULT_CONFIGURATION_PATH);
            _config = new XMLConfiguration(DEFAULT_CONFIGURATION_PATH);
            if(null!=_config) initialize();
             logger.info("Loaded {}",DEFAULT_CONFIGURATION_PATH);
        } catch (ConfigurationException ex) {
            logger.warn("Init Exception {}",ex.getMessage());
            logger.info("Loading {}",BUILD_IN_CONGIFUATION_PATH);

            try {
                _config = new XMLConfiguration(BUILD_IN_CONGIFUATION_PATH);
                 if(null!=_config) initialize();
                 logger.info("Loaded {}",BUILD_IN_CONGIFUATION_PATH);
            } catch (ConfigurationException ex1) {
                 logger.error("Init Exception {}",ex);
            }          

        }
    }

  //=========================================================================
  // RMQ Data
  //=========================================================================
    private static Map<String, RMQData> _rmqData = new HashMap<String, RMQData>();
    public RMQData getRMQData(){
        return getRMQData(DEFAULT_TEST_ENVIRONMENT);
    }
    public String getRMQHost(){
        return getRMQData().rmqHost;
    }
    public String getRMQExchange(){
        return getRMQData().rmqExchange;
    }
    public String getRMQUserName(){
        return getRMQData().rmqUserName;
    }
    //TODO decrypt
    public String getRMQUserPassword(){
        return getRMQData().rmqPassword;
    }
    public String getRMQName(){
        return getRMQData().rmqName;
    }

    private RMQData getRMQData(String string) {
        return _rmqData.get(string);
    }

    /** for web test only */
    public void setRMQData(RMQData rmqData ){
         setRMQData(DEFAULT_TEST_ENVIRONMENT, rmqData);
    }
    private void setRMQData(String string, RMQData rmqData) {
         _rmqData.put(string, rmqData);
    }

    //TODO data retrieved by using key

    public static class RMQData {

        public String rmqHost = "";
        public String rmqExchange = "";
        public String rmqUserName = "";
        public String rmqPassword = "";
        public String rmqName = ""; //DEV, QA, PROD, PTE

        @Override
        public String toString(){
            return new StringBuilder()
                    .append("\nrmqHost="+rmqHost)
                    .append("\nrmqExchange="+rmqExchange)
                    .append("\nrmqUserName="+rmqUserName)
                    .append("\nrmqPassword="+rmqPassword)
                    .append("\nrmqEnvironment="+rmqName)
                    .toString();
        }
    }

    //=========================================================================
    // Test Plan Data
    //=========================================================================
    private static Map<String, TestPlanData> _planData = new HashMap<String, TestPlanData>();
    public TestPlanData getTestPlanData(String env){
        return _planData.get(env);
    }
    public TestPlanData getTestPlanData(){
        return getTestPlanData(DEFAULT_TEST_ENVIRONMENT);
    }

    public int getPlanRepeat(){
        return getTestPlanData().repeat;
    }
    public boolean isPrintgbpsendEnabled(){
        return getTestPlanData().printgpbsend;
    }
    public boolean isPrintgpbEnabled(){
        return getTestPlanData().printgpb;
    }
    public boolean isPrintxmlEnabled(){
        return getTestPlanData().printxml;
    }
    public boolean isHIPAAEnabled(){
        return getTestPlanData().isHIPAA;
    }
    public boolean isRxStoreEnabled(){
        return getTestPlanData().rxstore;
    }
    public class TestPlanData {

        public List<String> runTestCases = new ArrayList<String>();
        public int repeat = 1;
        public boolean printxml = false;
        public boolean printgpb = false;
        public boolean printgpbsend = false;
        public boolean rxstore = false;
        public String name="";

        /** if web, HIPAA*/
        public boolean isHIPAA= true;

        @Override
        public String toString(){
            return new StringBuilder()
//                    .append("\nrmqHost="+rmqHost)

                    .toString();
        }
    }

    //=========================================================================
    // Test Data
    //=========================================================================

    private static Map<String, TestData> _testData = new HashMap<String, TestData>();
    public TestData getTestData(){
        return getTestData(DEFAULT_TEST_ENVIRONMENT);
    }

    public TestData getTestData(String key){
        return _testData.get(key);
    }

    public String[] getRxNumbers (){
         return getRxNumbers(DEFAULT_TESTDATA_NAME);
     }
    public String[] getRxNumbers (String name){
        TestData aTestData = getTestData(name);
        String[] returnValue = {};
        if(aTestData!=null){
            returnValue = aTestData.rxNumbers;
        }
        return returnValue;
    }

    public String getCustomerID (){
        return getCustomerID(DEFAULT_TESTDATA_NAME);
    }

    public String getCustomerID (String key){
        return getTestData(key).customerID;
    }

    public String getcounselingPharmacistID (){
        return getcounselingPharmacistID(DEFAULT_TESTDATA_NAME);
    }

    public String getcounselingPharmacistID (String key){
        return getTestData(key).counselingPharmacistID;
    }

    public String getDispendsarID (){
        return getDispendsarID(DEFAULT_TESTDATA_NAME);
    }

    public String getDispendsarID (String key){
        return getTestData(key).dispendsarId;
    }

    public String getPccID (){
        return getPccID(DEFAULT_TESTDATA_NAME);
    }

    public String getPccID (String key){
        return getTestData(key).dispendsarId;
    }

    

    public class TestData {
        public String name ="";
        public String customerID="";
        public String counselingPharmacistID="";
        public String dispendsarId="";
        public String pccId="";
        public String[] rxNumbers= {};
        
    }

    //=========================================================================
    // Init
    //=========================================================================
    private void initialize() {
        
            logger.info("[CONFIG] loading RMQ configuration");
            RMQData rmqData = new RMQData();
            rmqData.rmqHost = _config.getString("rmqConfiguration.rmqHost");
            rmqData.rmqExchange = _config.getString("rmqConfiguration.rmqExchange");
            rmqData.rmqUserName = _config.getString("rmqConfiguration.rmqUserName");
            rmqData.rmqPassword = _config.getString("rmqConfiguration.rmqPassword");
            rmqData.rmqName = _config.getString("rmqConfiguration.rmqName");
            _rmqData.put(rmqData.rmqName, rmqData);
            _currentEnvironment=rmqData.rmqName;
            //logger.info("rmqData={}", rmqData);

            //
            logger.info("[CONFIG] loading testplan configuration");            
            int index=0;
            while(true){
              TestPlanData testPlanData = new TestPlanData();
              String current = "testPlan.run("+(index++)+")";
              String name = _config.getString(current+".name");
              if(null==name) break; //TODO refactor.
              testPlanData.name=name;
              testPlanData.repeat=_config.getInt(current+".repeat");
              testPlanData.printgpbsend=_config.getBoolean(current+".printgpbsend");
              testPlanData.printgpb=_config.getBoolean(current+".printgpb");
              testPlanData.printxml=_config.getBoolean(current+".printxml");
              testPlanData.rxstore=_config.getBoolean(current+".rxstore");
              testPlanData.isHIPAA=_config.getBoolean(current+".hipaa");
              _planData.put(name, testPlanData);
              logger.info("testPlanData={}", testPlanData);
            }
            //TODO others.            
            
            //
            logger.info("[CONFIG] loading testdata configuration");            
            index=0;
            while(true){
              TestData testData = new TestData();
              String current = "testscenarios.testdata("+(index++)+")";
              testData.name = _config.getString(current+".name");
              if(null==testData.name) break; //TODO refactor.
              testData.customerID = _config.getString(current+".customerID");
              testData.counselingPharmacistID = _config.getString(current+".counselingPharmacistID");
              testData.dispendsarId = _config.getString(current+".dispendsarId");
              testData.pccId = _config.getString(current+".pccId");
              testData.rxNumbers = _config.getStringArray(current+".rxNumber");
              logger.info("testData={}", testData);
              _testData.put( testData.name, testData);
            }
            //TODO others.
            
       
    }
}
